package org.common.utils.config.handler;

import org.common.utils.config.ConfigException;
import org.common.utils.config.ConfigInfo;
import org.common.utils.config.ConfigObject;
import org.common.utils.config.ConfigType;
import org.common.utils.tool.StringTool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Map;
import java.util.Properties;

/**
 * 文件配置处理器
 * @author zhouzhibing
 * @date 2025/7/29
 */
public class FileHandler extends AbstractConfigHandler {

    private static final Logger log = LoggerFactory.getLogger(FileHandler.class);


    public FileHandler() {
        super(ConfigType.FILE);
    }

    @Override
    protected boolean loadImpl(ConfigObject configObject , ConfigInfo configInfo , Map<String , String> configMap) {
        String path = configInfo.getFilePath();
        if(StringTool.isEmpty(path)) {
            log.warn("FileHandler.loadImpl : path is null , ignore load .");
            return false;
        }

        File file = new File(path);
        if(!file.exists()) {
            ConfigException e = new ConfigException("FileHandler.loadImpl : file not exists , path = " + path);
            log.error("" , e);
            throw e;
        }

        Properties localProperties = new Properties();
        try {
            localProperties.load(new FileInputStream(file));
        } catch (IOException e) {
            throw new ConfigException(e);
        }
        localProperties.forEach((key , value) -> configMap.put(key.toString() , value.toString()));
        log.info("FileHandler.loadImpl success , path = {}" , path);
        return true;
    }
}
